package com.gis.halodepok;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.util.ByteArrayBuffer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ViewFlipper;

public class MenuKategori extends Activity {
	Context context;
	private LocationManager lm;
	private LocationListener locListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		int mFlipping = 0;

		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);

		ViewFlipper flipper = (ViewFlipper) findViewById(R.id.flipper);

		if (mFlipping == 0) {
			/** Start Flipping */
			flipper.startFlipping();
			mFlipping = 1;

		} else {
			/** Stop Flipping */
			flipper.stopFlipping();
			mFlipping = 0;

		}

		context = this;
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locListener = new MyLocationListener();
		if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 10,
					locListener);
		}

		File root = MenuKategori.this.getDir("haha", Context.MODE_PRIVATE);

		File dir = new File(root.getAbsolutePath() + "/xmls");
		if (!dir.exists()) {
			System.err.println("yolo 1");
			new AsyncTaskRunner().execute("");
		} else {

			Intent intentAlarm = new Intent(context, AlarmReciever.class);
			AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(System.currentTimeMillis());
			calendar.set(Calendar.HOUR_OF_DAY, 23);
			calendar.set(Calendar.MINUTE, 58);

			alarmManager.set(AlarmManager.RTC_WAKEUP, calendar
					.getTimeInMillis(), PendingIntent.getBroadcast(context, 0,
					intentAlarm, PendingIntent.FLAG_ONE_SHOT));

		}

		Button next = (Button) findViewById(R.id.rs);
		next.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						Rumahsakit.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next2 = (Button) findViewById(R.id.polisi);
		next2.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						Kepolisian.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next3 = (Button) findViewById(R.id.apotik);
		next3.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), Apotik.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next4 = (Button) findViewById(R.id.pemadam);
		next4.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), Pemadam.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next5 = (Button) findViewById(R.id.pemerintahan);
		next5.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						KantorPemerintah.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next6 = (Button) findViewById(R.id.bank);
		next6.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), MenuBank.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next7 = (Button) findViewById(R.id.bengkel);
		next7.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), Bengkel.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next8 = (Button) findViewById(R.id.galeri);
		next8.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), Galeri.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next9 = (Button) findViewById(R.id.service);
		next9.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), Service.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next10 = (Button) findViewById(R.id.percetakan);
		next10.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						Percetakan.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next11 = (Button) findViewById(R.id.hotel);
		next11.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						Penginapan.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next12 = (Button) findViewById(R.id.changer);
		next12.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						Moneychanger.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next13 = (Button) findViewById(R.id.sim);
		next13.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), Sim.class);
				startActivityForResult(myIntent, 0);
			}
		});

		Button next15 = (Button) findViewById(R.id.atm);
		next15.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), MenuAtm.class);
				startActivityForResult(myIntent, 0);
			}
		});
		
		Button next16 = (Button) findViewById(R.id.hangout);
		next16.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), MenuHangout.class);
				startActivityForResult(myIntent, 0);
			}
		});
		Button next17 = (Button) findViewById(R.id.taxi);
		next17.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), Taxi.class);
				startActivityForResult(myIntent, 0);
			}
		});
	}

	private class MyLocationListener implements LocationListener {
		@Override
		public void onLocationChanged(Location loc) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderDisabled(String provider) {
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

			// Setting Dialog Title
			alertDialog.setTitle("GPS is settings");

			// Setting Dialog Message
			alertDialog
					.setMessage("GPS is not enabled. Do you want to go to settings menu?");

			// On pressing Settings button
			alertDialog.setPositiveButton("Settings",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(
									Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							startActivity(intent);
						}
					});

			// on pressing cancel button
			alertDialog.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});

			// Showing Alert Message
			alertDialog.show();

		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

	}

	private class AsyncTaskRunner extends AsyncTask<String, String, String> {

		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = ProgressDialog.show(MenuKategori.this, "",
					"Loading. Please wait...", true);
		}

		public void DownloadFromUrl() {

			try {
				File root = MenuKategori.this.getDir("haha",
						Context.MODE_PRIVATE);

				File dir = new File(root.getAbsolutePath() + "/xmls");
				if (dir.exists() == false) {
					dir.mkdirs();
				}
				for (int i = 0; i < 27; i++) {
					URL url = new URL("http://hallodepok.herokuapp.com/" + i
							+ ".xml"); // you can write here any link
					File file = new File(dir, i + ".xml");
					if (file.exists() == false) {
						file.createNewFile();
					}
					long startTime = System.currentTimeMillis();
					Log.d("DownloadManager", "download begining");
					Log.d("DownloadManager", "download url:" + url);
					Log.d("DownloadManager", "downloaded file name:" + i
							+ ".xml");

					/* Open a connection to that URL. */
					URLConnection ucon = url.openConnection();

					/*
					 * Define InputStreams to read from the URLConnection.
					 */
					InputStream is = ucon.getInputStream();
					BufferedInputStream bis = new BufferedInputStream(is);

					/*
					 * Read bytes to the Buffer until there is nothing more to
					 * read(-1).
					 */
					ByteArrayBuffer baf = new ByteArrayBuffer(5000);
					int current = 0;
					while ((current = bis.read()) != -1) {
						baf.append((byte) current);
					}

					/* Convert the Bytes read to a String. */
					FileOutputStream fos = new FileOutputStream(file);
					fos.write(baf.toByteArray());
					fos.flush();
					fos.close();
					Log.d("DownloadManager",
							"download ready in"
									+ ((System.currentTimeMillis() - startTime) / 1000)
									+ " sec");
				}

			} catch (IOException e) {
				Log.d("DownloadManager", "Error: " + e);
			}

		}

		public Document getDomElement(String xml) {
			Document doc = null;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			try {

				DocumentBuilder db = dbf.newDocumentBuilder();

				InputSource is = new InputSource();
				is.setCharacterStream(new StringReader(xml));
				doc = db.parse(is);

			} catch (ParserConfigurationException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (SAXException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (IOException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			}
			// return DOM
			return doc;
		}

		// XML node keys

		private String resp;

		@Override
		protected String doInBackground(String... params) {
			DownloadFromUrl();
			return resp;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		menu.add(0, 0, 0, R.string.about);
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		super.onOptionsItemSelected(item);

		Team();
		return true;

	}

	private void Team() {
		Intent myIntent = new Intent(context, About.class);
		startActivityForResult(myIntent, 0);

	}

}
